package com.cicc.wm.lock.redis;

import com.cicc.wm.lock.DistributedLock;
import com.cicc.wm.lock.LockRegistry;
import lombok.extern.slf4j.Slf4j;
import org.redisson.api.RedissonClient;
import org.springframework.core.Ordered;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.atomic.AtomicBoolean;

/**
 * Redisson锁注册表
 * 实现Spring Integration的LockRegistry接口，提供基于Redisson的分布式锁
 */
@Slf4j
public class RedisLockRegistry implements LockRegistry, Ordered {
    private final RedissonClient redissonClient;
    private final Map<String, DistributedLock> locks = new ConcurrentHashMap<>();

    private final AtomicBoolean redisAvailable = new AtomicBoolean(true);

    public RedisLockRegistry(RedissonClient redissonClient) {
        this.redissonClient = redissonClient;
    }

    @Override
    public DistributedLock obtain(String lockKey) {
        return locks.computeIfAbsent(lockKey, key -> new RedisDistributedLock(redissonClient.getLock(key)));
    }

    @Override
    public boolean isActive() {
        try {
            // 尝试执行Redis ping命令检查连接
            redissonClient.getNodesGroup().pingAll();

            // 如果之前不可用，现在恢复了，记录日志
            if (!redisAvailable.getAndSet(true)) {
                log.info("Redis连接已恢复");
            }
            return true;
        } catch (Exception e) {
            // 如果之前可用，现在不可用了，记录日志
            if (redisAvailable.getAndSet(false)) {
                log.warn("Redis连接异常", e);
            }
            return false;
        }
    }

    @Override
    public int getOrder() {
        return 10;
    }
}
